﻿using System;
using System.Net;
using System.Threading;
using System.IO;
using Kiva7.Settings;

namespace Kiva7.Utilities
{

    public static class UsageMonitoring
    {
        const string FIRSTUSAGEURL = @"http://c.statcounter.com/7850720/0/972f0336/1/";

        public static void RegisterFirstUsage()
        {
            LoadUrl(UsageMonitoring.FIRSTUSAGEURL);
        }

        private static void LoadUrl(string url)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback((stateInfo) =>
            {
                try
                {
                    string statCounterCookie = AppSettings.Current.StatCounterCookie;

                    HttpWebRequest request = WebRequest.CreateHttp(url);

                    request.CookieContainer = new CookieContainer();
                    if (!string.IsNullOrEmpty(statCounterCookie))
                    {
                        Cookie c = new Cookie("is_unique", statCounterCookie, "/", ".statcounter.com");
                        c.Expires = DateTime.Now.AddYears(5);

                        request.CookieContainer.Add(new Uri("http://c.statcounter.com/"), c);
                    }

                    request.UserAgent = "KIVA7 (Windows Phone 7 application)";

                    IAsyncResult result = (IAsyncResult)request.BeginGetResponse(new AsyncCallback((asynchronousResult) =>
                    {
                        try
                        {
                            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
                            Cookie cookie = response.Cookies["is_unique"];

                            if (cookie != null
                                && string.IsNullOrEmpty(statCounterCookie))
                            {
                                AppSettings.Current.StatCounterCookie = cookie.Value;
                            }

                            StreamReader counter = new StreamReader(response.GetResponseStream());
                            counter.ReadToEnd();
                        }
                        catch { };
                    }),

                    null);
                }
                catch { };
            }));

        }

    }

}
